package com.titleevaluation.service;

import com.titleevaluation.entity.Application;
import com.titleevaluation.entity.Awards;
import com.titleevaluation.repository.ApplicationRepository;
import com.titleevaluation.repository.AwardsRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class AwardsService {

    private final AwardsRepository awardsRepository;
    private final ApplicationRepository applicationRepository;

    public AwardsService(AwardsRepository awardsRepository, ApplicationRepository applicationRepository) {
        this.awardsRepository = awardsRepository;
        this.applicationRepository = applicationRepository;
    }

    public Awards createAwards(Long applicationId, Awards awards) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        awards.setApplication(application);
        awards.setCreatedAt(LocalDateTime.now());
        awards.setUpdatedAt(LocalDateTime.now());
        return awardsRepository.save(awards);
    }

    public List<Awards> getAwardsByApplicationId(Long applicationId) {
        return awardsRepository.findByApplicationId(applicationId);
    }

    public Optional<Awards> getAwardsById(Long id) {
        return awardsRepository.findById(id);
    }

    public Awards updateAwards(Long id, Awards updatedAwards) {
        Awards existingAwards = awardsRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Awards not found"));

        existingAwards.setAwardType(updatedAwards.getAwardType());
        existingAwards.setAwardName(updatedAwards.getAwardName());
        existingAwards.setAwardDate(updatedAwards.getAwardDate());
        existingAwards.setAwardingDepartment(updatedAwards.getAwardingDepartment());
        existingAwards.setAwardNo(updatedAwards.getAwardNo());
        existingAwards.setPersonalRanking(updatedAwards.getPersonalRanking());
        existingAwards.setUpdatedAt(LocalDateTime.now());

        return awardsRepository.save(existingAwards);
    }

    public void deleteAwards(Long id) {
        awardsRepository.deleteById(id);
    }
}

